<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <tree-item
          :tree-node="company"
          is-root
          @addDepts="addDepts"
        />
        <!-- 组织架构 -->
        <el-tree
          default-expand-all
          :data="departs"
          :props="defaultProps"
          @node-click="handleNodeClick"
        >
          <tree-item
            slot-scope="{ data }"
            :tree-node="data"
            @delDepts="getDepartments"
            @addDepts="addDepts"
            @editDepts="editDepts"
          />
        </el-tree>
      </el-card>
    </div>
    <!-- 新增子部门 | 编辑部门 -->
    <add-dept
      ref="addDept"
      :title="title"
      :show-dialog.sync="showDialog"
      :tree-node="node"
      @addDepts="getDepartments"
    />
  </div>
</template>

<script>
import TreeItem from './components/tree-item'
import { getDepartments } from '@/api/departments'
import { formatTreeData } from '@/utils'
import AddDept from './components/add-dept' // 引入新增部门组件
export default {
  components: {
    TreeItem,
    AddDept
  },
  data() {
    return {
      title: '',
      company: { name: '江苏传智播客教育科技股份有限公司', manager: '负责人' },
      defaultProps: {
        label: 'name'
      },
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        },
        { name: '行政部', manager: '刘备' },
        { name: '人事部', manager: '孙权' }
      ],
      showDialog: false, // 显示窗体,
      // 当前操作节点
      node: null
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    handleNodeClick(data) {
      console.log(data)
    },
    async getDepartments() {
      const result = await getDepartments()
      this.company = { name: result.companyName, manager: '负责人', id: '' }
      this.departs = formatTreeData(result.depts, '') // 需要将其转化成树形结构
      console.log(result, this.departs)
    },
    addDepts(node) {
      this.title = '新增部门'
      this.showDialog = true // 显示弹层
      // 因为node是当前的点击的部门， 此时这个部门应该记录下来,
      this.node = node
    },
    editDepts(node) {
      this.title = '编辑部门'
      // 首先打开弹层
      this.showDialog = true
      this.node = node // 赋值操作的节点
      // 父组件 调用子组件的方法
      this.$refs.addDept.getDepartDetail(node.id) // 直接调用子组件中的方法 传入一个id
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
::v-deep .el-tree-node__content {
  margin: 6px 0;
}
</style>

